package com.example.maxboxtwo.utils.listeners;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;

import com.example.maxboxtwo.components.function.Compass.CompassView;

public class CompassListener implements SensorEventListener {
    private double angle = 0;
    private Integer oldDegree;

    private CompassView compassView;
    private float[] accelerate = new float[3];
    private float[] geomagnetic = new float[3];
    private float R[] = new float[9];
    private float values[] = new float[3];

    public CompassListener(CompassView compassView) {
        this.compassView = compassView;
    }

    public double getAngle() {
        return angle;
    }

    public void setAngle(double angle) {
        this.angle = angle;
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        switch (event.sensor.getType()){
            case Sensor.TYPE_ACCELEROMETER:
                accelerate = event.values;
                break;
            case Sensor.TYPE_MAGNETIC_FIELD:
                geomagnetic=event.values;
                break;
        }
        getZAxis();
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    public void getZAxis(){
        SensorManager.getRotationMatrix(R,null,accelerate,geomagnetic);
        SensorManager.getOrientation(R,values);
        values[0] = (float)Math.toDegrees(values[0]);
        //put the value of Z axis into angle
        setAngle(-values[0]);
        oldDegree = compassView.getDegree();
//        Log.i("sensor",values[0]+"");
        if (getAngle()>(oldDegree+5)||getAngle()<(oldDegree-5)){
        compassView.setDegree((int)Math.round(getAngle()));
        compassView.postInvalidate();
        }
    }
}
